import os
import sys
import logging as log
import shutil
import glob
import subprocess


class Fail(Exception):
    def __init__(self, text=None):
        self.t = text

    def __str__(self):
        return "ERROR" if self.t is None else self.t


def rm_one(d):
    d = os.path.abspath(d)
    if os.path.exists(d):
        if os.path.isdir(d):
            log.info("Removing dir: %s", d)
            shutil.rmtree(d)
        elif os.path.isfile(d):
            log.info("Removing file: %s", d)
            os.remove(d)


def check_dir(d, create=False, clean=False):
    d = os.path.abspath(d)
    if os.path.exists(d):
        if not os.path.isdir(d):
            raise Fail("Not a directory: %s" % d)
        if clean:
            for x in glob.glob(os.path.join(d, "*")):
                rm_one(x)
    else:
        if create:
            os.makedirs(d)
    return d


def isEmptyDir(d):
    files = os.listdir(d)
    return not len(files)


def execute(cmd, shell=False):
    try:
        log.debug("Executing: %s" % cmd)
        log.info('Executing: ' + ' '.join(cmd))
        retcode = subprocess.call(cmd, shell=shell)
        if retcode < 0:
            raise Fail("Child was terminated by signal: %s" % -retcode)
        elif retcode > 0:
            raise Fail("Child returned: %s" % retcode)
    except OSError as e:
        raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))


if __name__ == "__main__":
    log.basicConfig(format='%(message)s', level=log.DEBUG)
    if not os.path.exists("AndroidComUtils"):
        execute(
            ["git", "clone", "https://gitee.com/showwaychen/AndroidComUtils.git"])

log.info(" over !!!!")
